# -*- coding: utf-8 -*-
"""
创建目录json文件
"""
import os, json


def createCatalog(path):
    """
    将目标文件夹path生成目录
    :param path:
    :return:
    """
    catalog = {}
    index = 0
    for dirpath, dirnames, filenames in os.walk(path, topdown=True):
        if len(dirnames) != 0:
            num = 0
            for dirname in dirnames:
                num += 1
                catalog[num] = [dirname]  # 目录
            pass
        else:
            index += 1
            catalog[index].append(sorted(filenames, key=lambda a: int(a.replace(".jpg", ""))))  # p
            pass
    with open(path + ".json", "w") as fp:
        json.dump(catalog, fp)

    pass


def readCatalog(path):
    data = None
    with open(path) as fp:
        data = json.loads(fp.read(), encoding="utf-8")
    catalog = []
    p = {}
    for index in data:
        catalog.append(data[index][0])
        p[data[index][0]] = data[index][1]
    catalog.sort()
    return catalog, p


def read_or_greate(path):
    try:
        return readCatalog(path)
    except FileNotFoundError:
        createCatalog(path.replace(".json", ""))
        c, p = readCatalog(path)
        return c, p


if __name__ == "__main__":
    catalog, p = read_or_greate("关于我转生成为史莱姆这档事.json")
    print(catalog)
    print(len(catalog))
    print(catalog[-1])
